package com.bjpowernode.mvc.service.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.common.client.RedisClient;
import com.bjpowernode.common.consts.AppConst;
import com.bjpowernode.common.consts.Keys;
import com.bjpowernode.db.domain.AccountDetail;
import com.bjpowernode.db.domain.FinanceAccount;
import com.bjpowernode.db.domain.LoginDetail;
import com.bjpowernode.db.domain.User;
import com.bjpowernode.db.mapper.AccountDetailMapper;
import com.bjpowernode.db.mapper.FinanceAccountMapper;
import com.bjpowernode.db.mapper.LoginDetailMapper;
import com.bjpowernode.db.mapper.UserMapper;
import com.bjpowernode.db.result.UserAccountResult;
import com.bjpowernode.mvc.config.RealNameConfig;
import com.bjpowernode.mvc.model.dto.user.TokenUserDTO;
import com.bjpowernode.mvc.service.inter.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private FinanceAccountMapper financeAccountMapper;
    @Resource
    private AccountDetailMapper accountDetailMapper;
    @Resource
    private LoginDetailMapper loginDetailMapper;
    @Resource
    private RedisClient redisClient;
    /*@Resource
    private RealNameConfig realNameConfig;*/



    @Override
    public User queryByPhone(String phone) {

        //查询用户是否注册手机号
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        return userMapper.selectOne(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)  //回滚.
    @Override
    public synchronized int registerUser(String phone, String secret) {
        //默认.
        int result = -1;

        //查询手机号,是否注册
        User user = queryByPhone(phone);
        if (user == null) {
            //可以注册.
            String salt = UUID.randomUUID().toString().replaceAll("-", "");   //密码加盐,横线去掉.
            String newPassword = DigestUtil.md5Hex(secret + salt);
            //注册用户.
            User newUser = new User();
            newUser.setPhone(phone);
            newUser.setLoginPassword(newPassword);
            newUser.setAddTime(new Date());
            newUser.setSaltPassword(salt);
            userMapper.insert(newUser); //注册.

            //注册资金账户.
            FinanceAccount account = new FinanceAccount();
            account.setUid(newUser.getId());
            account.setAvailableMoney(new BigDecimal("99"));//体验金
            financeAccountMapper.insert(account);


            //记录账户资金变化
            AccountDetail accountDetail = new AccountDetail();
            accountDetail.setUid(newUser.getId());
            accountDetail.setAction(AppConst.ADD);
            accountDetail.setActionTime(new Date());
            accountDetail.setMoney(new BigDecimal("99"));
            accountDetail.setMemo("注册新用户,赠送体验金");

            accountDetailMapper.insert(accountDetail);

            result = 0;//成功.
        } else {
            return 1;//用户已经注册.
        }
        return result;
    }


    //登录访问用户.
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User userLogin(String phone, String secret, String LoginIp) {

        User user = queryByPhone(phone);
        if (user != null) {
            String loginPwd = user.getLoginPassword();
            String saltPwd = user.getSaltPassword();
            //二次加密.
            String newLoginPwd = DigestUtil.md5Hex(secret + saltPwd);
            if (loginPwd.equals(newLoginPwd)) { //这个位置.
                //比较一致,证明有效,更新登录时间
                user.setLastLoginTime((new Date()));
                userMapper.updateById(user);

                //添加登录流水.
                LoginDetail loginDetail = new LoginDetail();
                loginDetail.setUid(user.getId());
                loginDetail.setPhone(phone);
                loginDetail.setLoginTime(new Date());
                loginDetail.setLoginIp(LoginIp);

                loginDetailMapper.insert(loginDetail);
            } else {
                user = null;
           }
        }
        //
        return user;
    }


    //使用uuid表示token
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String createToken() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    //token是否存储成功.使用hash类型
    @Override
    public boolean saveTokenRedis(TokenUserDTO tokenUserDTO) {

        //redis的key
        String key = Keys.TOKEN_ACCESS + tokenUserDTO.getToken().toUpperCase();
        Map<String, String> data = new HashMap<>();
        data.put("id", String.valueOf(tokenUserDTO.getId()));
        data.put("name", StrUtil.isBlank(tokenUserDTO.getName()) ? "-" : tokenUserDTO.getName());
        data.put("phone", tokenUserDTO.getPhone());
        data.put("token", tokenUserDTO.getToken());
        return redisClient.addHash(key, data, 60);
    }


    //主键查用户
    @Override
    public User queryById(Integer userid) {
        return userMapper.selectById(userid);
    }


    @Transactional(rollbackFor = Exception.class)
    //实名认证.
    @Override
    public boolean hashRealname(Integer userid, String name, String idCard) {


        boolean handlerResult = false;
        boolean thirdResult = false;

     /* String result=  HttpClient.execHttpRequest(realNameConfig.getUrl(),
                                    realNameConfig.getAppcode()
                                    ,name,idCard);*/


        {

            String result = "{\n" +
                    "    \"code\": \"0\",\n" +
                    "    \"message\": \"成功\",\n" +
                    "    \"result\": {\n" +
                    "        \"name\": \"冯天\",\n" +
                    "        \"idcard\": \"350301198011129422\", \n" +
                    "        \"res\": \"1\", \n" +
                    "        \"description\": \"一致\", \n" +
                    "       \"sex\": \"男\",\n" +
                    "        \"birthday\": \"19940320\",\n" +
                    "        \"address\": \"江西省南昌市东湖区\"\n" +
                    "    }\n" +
                    "}";


            if (StrUtil.isNotBlank(result)) {
                //调用第三方接口,得到返回数据
                JSONObject resultObject = JSONUtil.parseObj(result);
                if ("0".equals(resultObject.getStr("code"))) {
                    //调用接口.
                    JSONObject resultJson = resultObject.getJSONObject("result");
                    if (resultJson != null) {
                        String res = resultJson.getStr("res");
                        if ("1".equals(res)) {
                            thirdResult = true;
                        }
                    }
                }
            }

            //判断认证结果.
            if (thirdResult) {
                //更新数据库
                User user = new User();
                user.setId(userid);
                user.setName(name);
                user.setIdCard(idCard);
                int rows = userMapper.updateById(user);
                if (rows < 1) {
                    throw new RuntimeException("实名认证,更新用户信息失败");
                }
                handlerResult = true;//实名认证业务逻辑处理成功.
            }

            return handlerResult;
        }
    }


    //查询用户和账户
    @Override
    public UserAccountResult queryUserAccountInfo(Integer userId) {
        UserAccountResult userAccountResult = userMapper.selectUserAccountById(userId);
        return userAccountResult;
    }





    //删除登录的token与key
    @Override
    public boolean removeLoginToken(String key) {

        return redisClient.deleteKey(key);

    }
}
